//
//  YTImageViewer.swift
//  YTImgeViewer
//
//  Created by aron on 2018/5/24.
//

import UIKit

open class YTImageViewerController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIViewControllerTransitioningDelegate, YTImageCellProtocol {

    /// 当前图片的位置
    public var currentImageIndex:Int = 0
    
    // 控制反转，依赖于具体分页对象的抽象，YTPagingProtocol是抽象借口，YTPagingObj是YTPagingProtocol一个具体实现
    // 外部可以实现YTPagingProtocol插入自定义的分页控件
    public var pagingModules: [YTPagingProtocol] = [YTPagingObj()]
    public var progressModules: YTImgeLoadProgressProtocol? = YTProgressObj()
    
    /// 用于显示图片数据
    lazy var images: [YTImage] = [YTImage]()
    
    /// 数据Delegate
    weak var delegate: YTImageDataProviderProtocol?
    
    private lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        return layout
    }()
    
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.isPagingEnabled = true
        collectionView.decelerationRate = UIScrollViewDecelerationRateFast
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.alwaysBounceVertical = false
        collectionView.register(YTImageCell.self, forCellWithReuseIdentifier: String(describing: YTImageCell.self))
        return collectionView
    }()
    
    // MARK:- Public
    
    // 显示图片
    static public func show(_ fromViewController: UIViewController, images: [YTImage], currentImageIndex: Int, delegate: YTImageDataProviderProtocol?) {
        let imageViewer = YTImageViewerController(delegate: delegate)
        imageViewer.images = images
        imageViewer.currentImageIndex = currentImageIndex
        
        fromViewController.present(imageViewer, animated: true, completion: nil)
    }
    
    // MARK:- Life Cycle

    init(delegate: YTImageDataProviderProtocol?) {
        self.delegate = delegate
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        // 向插件模块发送消息
        self.pagingModules.forEach { (pagingProtocolInstance: YTPagingProtocol) in
            pagingProtocolInstance.imageViewer(self, viewDidLoad: true)
        }
    }
    
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // FIXME: 处理第几张显示
//        // 处理第几张显示
//        if self.currentImageIndex >= self.images.count {
//            self.currentImageIndex = 0
//        }
//        self.collectionView.scrollToItem(at: IndexPath(item: currentImageIndex, section: 0), at: UICollectionViewScrollPosition.left, animated: true)
//
        // 向插件模块发送消息
        self.pagingModules.forEach { (pagingProtocolInstance: YTPagingProtocol) in
            pagingProtocolInstance.imageViewer(self, setCurrentPage: currentImageIndex, numberOfPages: self.images.count)
        }
    }

    override open func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    override open func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        setupViewFrame()
        
        // 向插件模块发送消息
        self.pagingModules.forEach { (pagingProtocolInstance: YTPagingProtocol) in
            pagingProtocolInstance.imageViewer(self, viewDidLayoutSubView: true)
        }
    }
    
    // MARK:- setup
    
    func setupUI() {
        self.view.addSubview(self.collectionView)
    }
    
    func setupViewFrame() {
        self.collectionView.frame = self.view.bounds
        layout.itemSize = self.view.bounds.size
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
    }
    
    // MARK:- UICollectionViewDataSource & UICollectionViewDelegate
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.images.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: YTImageCell.self), for: indexPath) as! YTImageCell
        cell.image = self.images[indexPath.item]
        cell.progressHandlerObj = progressModules
        cell.cellDelegate = self
        return cell
    }


    // MARK:- UICollectionViewDelegate
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
         
    }
    
    // MARK:- UIScrollViewDelegate
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let totalPage = self.images.count
        let curPage = Int(floor((scrollView.contentOffset.x / scrollView.frame.width) + 0.5))
        self.currentImageIndex = curPage
        // 向插件模块发送消息
        self.pagingModules.forEach { (pagingProtocolInstance: YTPagingProtocol) in
            pagingProtocolInstance.imageViewer(self, setCurrentPage: curPage, numberOfPages: totalPage)
        }
    }
    
    
    // MARK:- UIViewControllerTransitioningDelegate
    
    public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {

        // 布局
        setupUI()
        setupViewFrame()
        
        // 立即加载collectionView
        let indexPath = IndexPath(item: currentImageIndex, section: 0)
        collectionView.reloadData()
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        collectionView.layoutIfNeeded()
        let cell = collectionView.cellForItem(at: indexPath) as? YTImageCell
        
        let fromViewObj = transitionView()
        let fromView = fromViewObj.0
        
        let transitionToView = UIImageView()
        transitionToView.backgroundColor = UIColor.red
        
        var image: UIImage? = nil
        image = cell?.imageView.image
        if image == nil {
            image = fromViewObj.1
        }
        
        let transitionAnimatedView = UIImageView()
        transitionAnimatedView.image = fromViewObj.1
        transitionAnimatedView.backgroundColor = UIColor.green
        
        return YTScaleAnimator(transitionFromView: fromView, transitionToView: cell?.imageView, transitionAnimatedView: transitionAnimatedView)
    }
    
    public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        if self.collectionView.visibleCells.first == nil {
            return nil
        }
        
        let cell = self.collectionView.visibleCells.first as! YTImageCell
        
        let toViewObj = transitionView()
        let toView = toViewObj.0
        
        let transitionToView = UIImageView()
        transitionToView.backgroundColor = UIColor.red
        
        var image: UIImage? = nil
        image = cell.imageView.image
        if image == nil {
            image = toViewObj.1
        }
        
        let transitionAnimatedView = UIImageView()
        transitionAnimatedView.image = image
        transitionAnimatedView.backgroundColor = UIColor.green
        
        return YTScaleAnimator(transitionFromView: cell.imageView, transitionToView: toView, transitionAnimatedView: transitionAnimatedView)
    }
    
    /// 获取上一个页面对应的View
    func transitionView() -> (UIView?, UIImage?) {
        return (self.delegate?.imgageViewer(self, sourceViewForCurImageIndex: currentImageIndex))!
    }
    
    
    // MARK:- YTImageCellProtocol
    func imageCell(_ imageCell: YTImageCell, didSingleTap: Bool) {
        self.dismiss(animated: true) {
            
        }
    }
}
